package com.example.demo.common;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @ClassName StartupBrowserOpener
 * @Description 启动扩展类
 * @Author MingChang.Wei
 * @Date 2025/2/12
 **/
@Component
public class StartupBrowserOpener implements CommandLineRunner {
    Log log = LogFactory.get();

    @Value("${server.port:8181}")
    private String port;

    @Override
    public void run(String... args) throws Exception {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = currentTime.format(formatter);

        String url = "http://localhost:" + port;

        System.out.println("================================================================================================");
        System.out.println("应用启动时间：" + formattedTime);
        System.out.println("应用启动成功，访问地址：" + url);
        System.out.println("swagger API文档地址：" + url + "/swagger-ui.html");
        System.out.println("springDoc+knife4j API增强文档地址：" + url + "/doc.html");
        System.out.println("================================================================================================");

        openBrowser(url);
    }

    private void openBrowser(String url) {
        try {
            String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                Desktop.getDesktop().browse(new URI(url));
            } else if (os.contains("win")) {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            } else if (os.contains("mac")) {
                Runtime.getRuntime().exec("open " + url);
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                log.info("linux系统无法自动打开浏览器，请手动访问：{}", url);
            } else {
                log.info("无法自动打开浏览器，请手动访问：{}", url);
            }
        } catch (IOException | URISyntaxException e) {
            log.error("无法自动打开浏览器：{}，请手动访问：{}", e.getMessage(), url);
        }
    }
}
